﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FileConvertPdfSystemBLL;
using FileConvertPdfSystemModel;

using System.IO;
using System.Diagnostics;
using System.Threading;

namespace FileConvertPdfSystemWeb
{
    public partial class UserLoginSuccess : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //killexcel();
                FileConvertPdfSystemBLL.UserInformation1 user=new FileConvertPdfSystemBLL.UserInformation1();
                Label1.Text = Convert.ToString(Session["UserNameLogin"]) + "您好！";
                LabLoginTime.Text = DateTime.Now.ToString();
                LabScore.Text = user.Get_SingUserInformation(Convert.ToString(Session["UserNameLogin"])).Score.ToString();
                File_Share2 files = new File_Share2();
                Gri.DataSource = files.Get_File();
                Gri.DataBind();
            }
        }

        protected void Gri_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.Gri.PageIndex = e.NewPageIndex;
            File_Share2 files = new File_Share2();
            Gri.DataSource = files.Get_File();
            Gri.DataBind();

        }

        protected void Button5_Click(object sender, EventArgs e)
        {
            string skeyname = Convert.ToString(Session["UserNameLogin"]);
            Cache.Remove(skeyname);
            Session["userLayout"] = "exit";
            Response.Redirect("Default.aspx");
            Response.End();
        }



        protected void Timer1_Tick(object sender, EventArgs e)
        {
            LabLoginTime.Text = DateTime.Now.ToString();
        }

        protected void Gri_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            Response.Write("<script>alert('test1');</script>");
        }
        public void killexcel()
        {
            foreach (Process proc in System.Diagnostics.Process.GetProcesses())
            {
                int begpos;
                int endpos;

                string sProcName = proc.ToString();
                begpos = sProcName.IndexOf("(") + 1;
                endpos = sProcName.IndexOf(")");

                sProcName = sProcName.Substring(begpos, endpos - begpos);

                if (sProcName.ToLower().CompareTo("excel") == 0)
                {
                    try
                    {
                        proc.Kill();
                    }
                    catch { }
                    break;
                }
            }
        }
        private void RecordFile()
        {
            File_Share2 file = new File_Share2();
            FileConvertPdfSystemModel.File_share file_model = new FileConvertPdfSystemModel.File_share();
            file_model.File_ID = 12;
            file_model._File_Name = FileUpload2.FileName;
            file_model._File_UploadTime = DateTime.Now;
            file.Add_File_Share(file_model);
            Data();

        }
        private void convertopdf_killexcelCompleted(object sender, File_ManageSystemWeb.FileConvertPdf.killexcelCompletedEventArgs e)
        {
            killexcel();
        }
        string file_share = @"C:\" + "File_Convertpdf" + @"\" + "share_file" + @"\";
        protected void BtnLoginSuccessUpload_Click(object sender, EventArgs e)
        {
            int word = 0, excel = 0, powerpoint = 0;
            string judefileexten="";
            string storefolder = @"C:\" +"File_Convertpdf"+ @"\"+ "user"+@"\"+
                Convert.ToString(Session["UserNameLogin"]) + @"\";
            string storeuploadFile = storefolder + "upload" + @"\";
            string storedownFile = storefolder + "Download" + @"\";

            DirectoryInfo di = new DirectoryInfo("" + storefolder);
            DirectoryInfo di_upload = new DirectoryInfo("" + storeuploadFile);
            DirectoryInfo di_download = new DirectoryInfo("" + storedownFile);

            di.Create();
            di_upload.Create();
            di_download.Create();

            FileConvertPdfSystemModel.LoginUserFileDown FileDown = new FileConvertPdfSystemModel.LoginUserFileDown();
            LoginUserFileDownBLL FileDownBLL = new LoginUserFileDownBLL();
            UserInformation1 UserInfoBll = new UserInformation1();


            bool ex = false;
            File_ManageSystemWeb.FileConvertPdf.ConvertFiletoPdf convertopdf = new File_ManageSystemWeb.FileConvertPdf.ConvertFiletoPdf();
            if (FileUpload2.HasFile)
            {
                if (FileUpload2.FileName.Contains(".xlsx") || FileUpload2.FileName.Contains(".docx")||
                    FileUpload2.FileName.Contains(".pptx") || FileUpload2.FileName.Contains(".ppt") ||
                    FileUpload2.FileName.Contains(".doc") || FileUpload2.FileName.Contains(".xls"))
                {
                    string sourcefile = storeuploadFile + FileUpload2.FileName;
                    FileInfo file1 = new FileInfo(FileUpload2.PostedFile.FileName);
                    //if (file1.Extension==".xlsx")
                    judefileexten=file1.Extension;
                    string outputfile="";
                    switch (judefileexten)
                    {
                        case ".xlsx": 
                            excel = 1;
                            outputfile = storedownFile + FileUpload2.FileName.Replace(".xlsx", ".pdf");
                            break;
                        case ".docx":
                            word = 1;
                            outputfile = storedownFile + FileUpload2.FileName.Replace(".docx", ".pdf");
                            break;
                        case ".pptx":
                            powerpoint = 1;
                            outputfile = storedownFile + FileUpload2.FileName.Replace(".pptx", ".pdf");
                            break;
                        case ".xls":
                            excel = 1;
                            outputfile = storedownFile + FileUpload2.FileName.Replace(".xls", ".pdf");
                            break;
                        case ".doc":
                            word = 1;
                            outputfile = storedownFile + FileUpload2.FileName.Replace(".doc", ".pdf");
                            break;
                        case ".ppt":
                            powerpoint = 1;
                            outputfile = storedownFile + FileUpload2.FileName.Replace(".ppt", ".pdf");
                            break;

                    }
                    

                    if (RadioButton1.Checked)
                    {
                        DirectoryInfo di_share = new DirectoryInfo("" + file_share);
                        di_share.Create();
                        string file_path = file_share + FileUpload2.FileName;
                        File_Share2 fileshare = new File_Share2();
                        File_share  filemodel=new File_share();
                        filemodel._File_Name=FileUpload2.FileName;
                        filemodel._File_UploadTime=DateTime.Now;
                        fileshare.Add_File_Share(filemodel);
                        FileUpload2.SaveAs(file_path);
                    }

                    FileDown.File_Size=FileUpload2.PostedFile.ContentLength/(1024);
                    FileDown.File_Name = FileUpload2.FileName;
                    FileDown.File_ID = 1;
                    FileDown.User_ID = UserInfoBll.Get_SingUserInformation(Session["UserNameLogin"].ToString()).ID;

                    FileDown.File_UploadTime = DateTime.Now;
                    FileDown.User_Name = Session["UserNameLogin"].ToString();
                    FileDownBLL.Add_LoginUserFileDown(FileDown);

                    //Save original file
                    FileUpload2.SaveAs(sourcefile);

                    //call the converter method
                    //converter.Convert4(sourcefile, outputfile);
                    //service
                    //service.init();
                    if (excel==1)
                    {
                        ex = convertopdf.str(sourcefile, outputfile);
                    }
                    if (word==1)
                    {
                        ex = convertopdf.str2(sourcefile, outputfile);

                    }
                    if (powerpoint==1)
                    {
                        ex = convertopdf.str1(sourcefile, outputfile);

                    }
                    
                    if (ex == false)
                    {
                        Response.Write("<script>alert('convet pdf failed!');</script>");
                    }
                    else
                    {
                        if(File.Exists(outputfile)==true)
                        {
#region   whichout code 

                          //convertopdf.killexcelAsync();
                          //convertopdf.killexcelCompleted+=new FileConvertPdf.killexcelCompletedEventHandler(convertopdf_killexcelCompleted);
                          //if(convertopdf.killexcel()==false)
                          //    Response.Write("<script>alert('kill excel failed!');location.href='UserLoginSuccess.aspx';</script>");
                            //killexcel();
#endregion
                            Response.Write("<script>alert('convet pdf successful!'); location.href='UserLoginSuccess.aspx';</script>");
                        }
                        else
                        {
#region 

                            //if(convertopdf.killexcel()==false)
                            //    Response.Write("<script>alert('kill excel failed!');location.href='UserLoginSuccess.aspx';</script>");
                            //killexcel();
                            //convertopdf.killexcelAsync();
                            //convertopdf.killexcelCompleted += new FileConvertPdf.killexcelCompletedEventHandler(convertopdf_killexcelCompleted);
#endregion
                            LoginUserConvertpdfQueue LoginModel = new LoginUserConvertpdfQueue();
                            LoginUserConvertpdfQueueBLL LoginBll = new LoginUserConvertpdfQueueBLL();
                            LoginModel.User_Name = Session["UserNameLogin"].ToString();
                            LoginModel.User_Score = UserInfoBll.Get_SingUserInformation(Session["UserNameLogin"].ToString()).Score;
                            LoginModel.File_Name = FileUpload2.FileName;
                            LoginBll.Add_LoginUserConvertpdfQueue(LoginModel);
                            Response.Write("<script>alert('add convert queue!');location.href='UserLoginSuccess.aspx';</script>");

                        }
                    }
                    //convertopdf.killexcelAsync();
                    //convertopdf.killexcelCompleted += new FileConvertPdf.killexcelCompletedEventHandler(convertopdf_killexcelCompleted);

                    //Thread.Sleep(2000);
                    //if (convertopdf.killexcel() == false)
                    //    Response.Write("<script>alert('kill excel failed!');location.href='UserLoginSuccess.aspx</script>");
                    convertopdf.Dispose();
                    //System.IO.File.Delete(sourcefile);
                }
            }
            else
            {
                Response.Write("<script>alert('请选择上传文件!');location.href='UserLoginSuccess.aspx';</script>");
            }
        }

        private void Data()
        {
            File_Share2 files = new File_Share2();
            Gri.DataSource = files.Get_File();
            Gri.DataBind();

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            //File_Share2 file = new File_Share2();
            //FileConvertPdfSystemModel.File_share file_model = new FileConvertPdfSystemModel.File_share();
            //file_model.File_ID = 12;
            //file_model._File_Name = "ab";
            //file_model._File_UploadTime = DateTime.Now;
            //file.Add_File_Share(file_model);
            //Data();
            //string storefolder = @"d:\" + Convert.ToString(Session["UserNameLogin"]) + @"\";
            //string storeuploadFile = storefolder + "upload" + @"\";
            //string storedownFile = storefolder + "Download" + @"\";
            //DirectoryInfo di = new DirectoryInfo("" + storefolder);
            //DirectoryInfo di_upload = new DirectoryInfo("" + storeuploadFile);
            //DirectoryInfo di_download = new DirectoryInfo("" + storedownFile);

            //di.Create();
            //di_upload.Create();
            //di_download.Create();

            //bool ex = false;
            //FileConvertPdf.ConvertFiletoPdf convertopdf = new FileConvertPdf.ConvertFiletoPdf();
            //if (FileUpload1.HasFile)
            //{
            //    if (FileUpload1.FileName.Contains(".xlsx"))
            //    {
            //        string sourcefile = storefolder + FileUpload1.FileName;
            //        string outputfile = storefolder + FileUpload1.FileName.Replace(".xlsx", ".pdf");

            //        //Save original file
            //        FileUpload1.SaveAs(sourcefile);

            //        ex = convertopdf.str(sourcefile, outputfile);
            //        if (ex == false)
            //        {
            //            Response.Write("<script>alert('convet pdf failed!');</script>");
            //        }
            //        else
            //        {
            //            if (File.Exists(outputfile) == true)
            //            {
            //                Response.Write("<script>alert('convet pdf successful!'); location.href='UserLoginSuccess.aspx';</script>");
            //            }
            //            else
            //            {
            //                Response.Write("<script>alert('add convert queue!');location.href='UserLoginSuccess.aspx';</script>");
            //            }
            //        }
            //        convertopdf.Dispose();
            //        System.IO.File.Delete(sourcefile);
            //    }
            //}


        }

        protected void BtnLoginSuccessfulDownload_Click(object sender, EventArgs e)
        {
            Response.Redirect("LoginUserDownLoad.aspx");
            Response.End();

        }

        protected void Button_Upload_Click(object sender, EventArgs e)
        {
            File_Share2 file = new File_Share2();
            FileConvertPdfSystemModel.File_share file_model = new FileConvertPdfSystemModel.File_share();
            file_model.File_ID = 12;
            file_model._File_Name = "ab";
            file_model._File_UploadTime = DateTime.Now;
            file.Add_File_Share(file_model);
            Data();
        }

        protected void Gri_RowCancelingEdit2(object sender, GridViewCancelEditEventArgs e)
        {
            string storedownFile = file_share + Gri.Rows[e.RowIndex].Cells[1].Text;
            string path = storedownFile;

            FileInfo fi = new FileInfo(path);

            if (fi.Exists)
            {
                Response.Clear();
                Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(fi.Name));
                Response.AddHeader("Content-Length", fi.Length.ToString());
                Response.ContentType = "application/octet-stream";
                Response.Filter.Close();
                Response.WriteFile(fi.FullName);
                Response.End();
            }

        }
    }
}